package com.boe.csb.core.common.utils;

import com.alibaba.csb.console.sdk.ConsoleHttpCaller;
import com.alibaba.csb.console.sdk.ConsoleSdkUtils;
import com.alibaba.csb.console.sdk.Result;
import com.alibaba.csb.console.sdk.param.Parameter;
import com.alibaba.csb.console.sdk.param.ParamsBuilder;
import com.boe.csb.core.common.CsbConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

import static com.boe.csb.core.common.CsbConstants.CSB_ADMIN_LOGINID;
import static com.boe.csb.core.common.CsbConstants.CSB_INSTANCE_NAME;

/**
 * Created by tianjin.lp on 16/11/22.
 */
public class CsbApiCaller {

    private static final Logger logger = LoggerFactory.getLogger(CsbApiCaller.class);

    //初始化CSB_ID
    //todo 后续修改为真正的用户和csbId
    public static String CSB_ID = getCsbId();
    public static String CSB_ADMIN_ID = getCsbUserId();


    public static Result callCsbGetApi(String apiName, Map<String, String> queryParams) {
        logger.info("开始调用csb api,apiName=" + apiName + ",apiParams=" + queryParams);
        ParamsBuilder builder = new ParamsBuilder();
        for (Map.Entry<String, String> entry : queryParams.entrySet()) {
            builder.append(new Parameter(entry.getKey(), entry.getValue()));
        }
        String resultStr = ConsoleHttpCaller.doGet(CsbConstants.CSB_API_HOST, apiName, builder.toString(), null, CsbConstants.CSB_API_AK, CsbConstants.CSB_API_SK);
        Result result = ConsoleSdkUtils.getCheckedResult(resultStr);
        logger.info("调用csb api完毕,apiName=" + apiName + ",return str=" + GsonUtils.object2String(result));
        return result;
    }


    public static Result callCsbPostApi(String apiName, Map<String, String> queryParams, String jsonParams) {
        String queryStr = null;
        ParamsBuilder builder = new ParamsBuilder();
        if (queryParams != null && queryParams.size() > 0) {
            builder.append(new Parameter("csbId", CSB_ID));
            for (Map.Entry<String, String> entry : queryParams.entrySet()) {
                builder.append(new Parameter(entry.getKey(), entry.getValue()));
            }
            queryStr = builder.toString();
            builder.clear();
        }
        builder = new ParamsBuilder();
        if (jsonParams != null) {
            builder.append(new Parameter("data", jsonParams));
        }
        String bodyStr = builder.toString();
        logger.info("开始调用csb api,apiName=" + apiName + ",queryParams=" + queryParams + ",jsonParams=" + jsonParams);
        String resultStr = ConsoleHttpCaller.doPost(CsbConstants.CSB_API_HOST, apiName, queryStr, bodyStr, CsbConstants.CSB_API_AK, CsbConstants.CSB_API_SK);
        logger.info("调用返回串: " + resultStr);
        Result result = ConsoleSdkUtils.getCheckedResult(resultStr);
        logger.info("调用csb api完毕,apiName=" + apiName + ",return str=" + GsonUtils.object2String(result));
        return result;
    }

    private static String getCsbId() {
        String csbId = null;
        try {
            ParamsBuilder builder = new ParamsBuilder();
            builder.append(new Parameter("csbName", CSB_INSTANCE_NAME));
            String resultStr = ConsoleHttpCaller.doGet(CsbConstants.CSB_API_HOST, "api/admin/csbinstance/info", builder.toString(), null, CsbConstants.CSB_API_AK, CsbConstants.CSB_API_SK);
            Result result = ConsoleSdkUtils.getCheckedResult(resultStr);
            csbId = result.getId("csb");
            logger.info(String.format("CSB ID初始化成功, CSB_ID is %s", csbId));
        } catch (Exception e) {
            logger.error("CSB实例初始化失败,获取CSB ID失败..,CSB_INSTANCE_NAME=" + CSB_INSTANCE_NAME, e);
        }
        return csbId;
    }

    private static String getCsbUserId() {
        String userId = null;
        try {
            ParamsBuilder builder = new ParamsBuilder();
            builder.append(new Parameter("loginId", CSB_ADMIN_LOGINID));
            String resultStr = ConsoleHttpCaller.doGet(CsbConstants.CSB_API_HOST, "api/admin/user/info", builder.toString(), null, CsbConstants.CSB_API_AK, CsbConstants.CSB_API_SK);
            Result result = ConsoleSdkUtils.getCheckedResult(resultStr);
            userId = result.getData().getJSONObject("user").getString("userId");
            logger.info(String.format("CSB ADMIN USER ID初始化成功, ADMIN_USER_ID is %s", userId));
        } catch (Exception e) {
            logger.error("CSB ADMIN USER实例初始化失败,获取ADMIN_USER_ID失败..,CSB_ADMIN_LOGINID=" + CSB_ADMIN_LOGINID, e);
        }
        return userId;
    }

}
